<template>
  <div class="userAvatar">
    <el-card class="box-card">
      <div slot="header" class="clearfix ">
        <span class="text">更换头像</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item>
          <img  v-if="!src" src="./assets/avatar.jpg"  alt='图片预览' />
          <img v-else ref="previewImage"  :src="src"  alt='图片预览' />
          <div class="filelabel">
              <el-button class="changeButton" @click="selectImg()">+ 选择头像</el-button>
              <input ref="inputFile" style="display:none"  id="inputFile"  @change="Imgchange"  type="file" accept="image/*" />
              <el-button class="chooseButton" @click="onSubmit()">⬆ 上传图片</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ImgTO64BitString } from '@/utils/imgs'
export default {
  data () {
    return {
      form: {
        avatar: ''
      },
      rules: {},
      src: ''
    }
  },
  methods: {
    // 封面图片变化
    Imgchange () {
      const file = this.$refs.inputFile.files[0]
      this.src = file ? URL.createObjectURL(file) : ''
      this.form.avatar = file
      console.log(this.form.avatar)
    },
    // 选择头像
    selectImg () {
      this.$refs.inputFile.click()
    },
    // 上传头像
    async onSubmit () {
      try {
        if (this.form.avatar) {
          // 调用封装的getBase64方法，将图片文件转化base64格式的字符串
          this.form.avatar = await ImgTO64BitString(this.form.avatar)
          const res = await this.$store.dispatch('user/changeUserAvatarAction', this.form)
          console.log(res)
          location.reload()
        } else {
          window.alert('未选择头像')
        }
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 1126px;
    ::v-deep .el-card__header{
      height: 68px;
      .text {
        font-size: 16px;
        margin: 5px 0;
        font-weight: 600;
      }
    }
    ::v-deep .el-form {
      img{
        width: 226px;
        height: 226px;
      }
      // 按钮效果
      .changeButton,.chooseButton{
          padding: 5px 16px;
          height: 32px;
      }
      .changeButton{
          width: 108px;
          background-color: #4F81FF ;
          color: #FFF;
          &:hover{
              background-color:#608DFF ;
          }
      }
      .chooseButton{
          width: 108px;
          background-color: #8f9397;
          color: #fff;
          &:hover{
            background-color:#a1a6ac;
          }
      }
    }
  }
</style>
